package cn.outsourcing.supermarket.service.impl;

import cn.outsourcing.supermarket.common.constants.CommonConstants;
import cn.outsourcing.supermarket.common.utils.DataUtils;
import cn.outsourcing.supermarket.common.utils.JwtUtils;
import cn.outsourcing.supermarket.mapper.HiolabsSearchHistoryMapper;
import cn.outsourcing.supermarket.po.HiolabsSearchHistory;
import cn.outsourcing.supermarket.service.HiolabsSearchHistoryService;
import cn.outsourcing.supermarket.vo.SearchHistoryVO;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author gzkemays
 * @since 2021-10-23
 */
@Service
public class HiolabsSearchHistoryServiceImpl
    extends ServiceImpl<HiolabsSearchHistoryMapper, HiolabsSearchHistory>
    implements HiolabsSearchHistoryService {
  @Resource HiolabsSearchHistoryMapper historyMapper;
  @Autowired HttpServletRequest request;

  @Override
  public SearchHistoryVO getSearchHistory() {
    Integer userId =
        (Integer) JwtUtils.getTokenClaimByRequest(request, CommonConstants.TOKEN_USER_ID_KEY);
    // 返回用户搜索记录列表
    List<String> histories =
        historyMapper
            .selectList(
                Wrappers.<HiolabsSearchHistory>lambdaQuery()
                    .eq(HiolabsSearchHistory::getUserId, userId))
            .stream()
            .map(HiolabsSearchHistory::getKeyword)
            .collect(Collectors.toList());
    return SearchHistoryVO.builder().historyKeywordList(histories).build();
  }

  @Override
  public void insertHistory(String keyword) {
    Integer userId =
        (Integer) JwtUtils.getTokenClaimByRequest(request, CommonConstants.TOKEN_USER_ID_KEY);
    if (noneHistory(keyword)) {
      historyMapper.insert(
          HiolabsSearchHistory.builder()
              .keyword(keyword)
              .addTime(DataUtils.getSeconds())
              .userId(String.valueOf(userId))
              .build());
    }
  }

  @Override
  public boolean noneHistory(String keyword) {
    Integer userId =
        (Integer) JwtUtils.getTokenClaimByRequest(request, CommonConstants.TOKEN_USER_ID_KEY);
    Integer count =
        historyMapper.selectCount(
            Wrappers.<HiolabsSearchHistory>lambdaQuery()
                .eq(HiolabsSearchHistory::getKeyword, keyword)
                .eq(HiolabsSearchHistory::getUserId, userId));
    return count == 0;
  }
}
